package com.lanchetech.admin.erp;

import com.alibaba.fastjson.JSON;
import com.lanchetech.common.enums.ResultCode;
import com.lanchetech.common.exception.ResultCodeException;
import io.swagger.annotations.ApiOperation;
import org.apache.commons.lang3.StringUtils;
import org.apache.ibatis.annotations.Param;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.web.bind.annotation.*;
import springfox.documentation.annotations.ApiIgnore;

import javax.servlet.http.HttpServletRequest;
import java.io.IOException;
import java.util.HashMap;
import java.util.Map;

import static com.lanchetech.admin.erp.JuShuiTanUtil.getAccessToken;

@RestController
@RequestMapping("/api/JuShuiTan")
public class JuShuiTanController {

    private final org.slf4j.Logger log = LoggerFactory.getLogger(this.getClass());

    /**
     * 授权URL有效时间为15分钟，生成链接之后，请尽快让商家登录授权
     *
     * @param juShuiTanQuery
     * @return
     */
    @ApiOperation("获取授权的URL")
    @ResponseBody
    @RequestMapping(value = "/auth/url", method = RequestMethod.POST)
    public void getAuthorizationUrl(@RequestBody JuShuiTanQuery juShuiTanQuery) {
        String url = null;
        try {
            url = JuShuiTanUtil.spliceAuthorizationUrl(juShuiTanQuery.getState());
        } catch (IOException e) {
            log.error("IO异常:{}", e.getMessage());
            e.printStackTrace();
        }
        System.out.println(url);
    }

    /**
     * 回调验证是否开启
     */
    @Value("${jushuitan.callBack.signature}")
    private Boolean signature;
    @Value("${jushuitan.token}")
    private String token;

    /**
     * 授权码有效期仅有15分钟，超时则需要重新生成授权链接，由商家重新授权。
     *
     * @return 商家点击确认授权之后，聚水潭平台便会通过回调地址返回code。
     * 授权回调的接口如下：GET的请求方式。
     * 是否验签可以由开发者自己决定。
     */
    @ApiIgnore
    @ApiOperation("授权回调")
    @ResponseBody
    @RequestMapping(value = "/auth/callBack", method = RequestMethod.GET)
    public Object callBackAuthorization() {

        HttpServletRequest httpServletRequest = getHttpServletRequest();

        String app_key = httpServletRequest.getParameter("app_key");
        String code = httpServletRequest.getParameter("code");
        String state = httpServletRequest.getParameter("state");
        String sign = httpServletRequest.getParameter("sign");

        log.info("聚水潭授权回调：appKey-{},code-{},state-{},sign-{}", app_key, code, state, sign);

        //验签
        Map<String, String> params = new HashMap<>();
        params.put("app_key", app_key);
        params.put("code", code);
        params.put("state", state);
        try {
            //验签结果
            Boolean signatureVerification = true;

            if (signature) {
                //验证签名
                signatureVerification = JuShuiTanUtil.signatureVerification(params, sign);
            }

            if (signatureVerification) {
                //获取AccessToken
                getAccessToken(code);
            } else {
                log.error("验签失败！！！");
                throw new ResultCodeException(ResultCode.ACTIVE_CODE_INVALID);
            }
        } catch (IOException e) {
            log.error("IO异常：{}", e.getMessage());
            e.printStackTrace();
        } catch (ResultCodeException e) {
            log.error("状态异常：{}", e.getMessage());
            throw new RuntimeException(e);
        }
        Map<String, Object> result = new HashMap<>();
        result.put("code", 0);
        result.put("msg", "success");
        return JSON.toJSON(result);
    }

    private HttpServletRequest getHttpServletRequest() {
        return null;
    }

    /**
     * 店铺查询
     *
     * @param index 第几页，默认第一页
     * @param size  每页多少条；默认100条，最大100条
     * @param nicks 店铺主账号，不支持模糊查询，非必填项，默认查所有
     * @return
     * @throws IOException
     */
    @GetMapping("shopQuery")
    public String shopQuery(@RequestParam(value = "index", defaultValue = "1", required = false) Integer index,
                            @RequestParam(value = "size", defaultValue = "10", required = false) Integer size,
                            @RequestParam(value = "nicks", defaultValue = "", required = false) String nicks) throws IOException {
        String accessToken = token;
        String url = "/open/shops/query";
        //请求参数
        Map<String, Object> params = new HashMap<>();
        params.put("page_index", index);
        params.put("page_size", size);
        if (!StringUtils.isEmpty(nicks)) {
            String[] split = nicks.split(",");
            params.put("nicks", split);
        }
        String biz = JSON.toJSONString(params);
        String result = JuShuiTanUtil.sendRequest(accessToken, params, url);
        return result;
    }


}
